#pragma once
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include "Log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
#include "Err.hpp"
#include <cstring>
using namespace std;
static const int gbacklog=1;
class Sock
{
public:
    void Socket()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            LogMessage(Fatal, "socket error");
            exit(SOCKET_ERR);
        }
        int option=1;
         setsockopt(_sock,SOL_SOCKET,SO_REUSEADDR,&option,sizeof(option));
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_addr.s_addr = INADDR_ANY; // 云服务器不需要指定IP
        local.sin_family = AF_INET;         // IPv4
        local.sin_port = htons(port);       // 要记得改变调整成网络字节序
        int n = bind(_sock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LogMessage(Fatal, "Bind error,sterror(errno):%s",strerror(errno));
            exit(BIND_ERR);
        }
    }

    void Listen()
    {
        int n=listen(_sock,gbacklog);
        if(n<0)
        {
            LogMessage(Fatal,"Listen error");
            exit(LISTEN_ERR);
        }
    }

    int Accept(string& clientip,uint16_t& clientport)
    {
        struct sockaddr_in client;
        socklen_t len;
        int n=accept(_sock,(struct sockaddr*)&client,&len);
        if(n<0)
        {
            LogMessage(Fatal,"accept error");
            exit(ACCEPT_ERR);
        }

        clientip=inet_ntoa(client.sin_addr);//记得转换成字符串
        clientport=ntohs(client.sin_port);
        return n;
    }


private:
    int _sock;
};